package secret

import (
	"bytes"
	"crypto/des"
	"encoding/base64"
	"fmt"
	"log"
)

// PKCS5Padding 实现，与PKCS7Padding在块大小为8字节时相同
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

// PKCS5Unpadding 实现
func pkcs5Unpadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

// Decrypt3DES 使用3DES/ECB/PKCS5Padding解密数据
func Decrypt3DES(encryptedBase64 string, key []byte) (string, error) {
	// 解码Base64
	encrypted, err := base64.StdEncoding.DecodeString(encryptedBase64)
	if err != nil {
		return "", err
	}

	// 创建3DES块密码
	block, err := des.NewTripleDESCipher(key)
	if err != nil {
		return "", err
	}

	// ECB模式解密（手动实现）
	if len(encrypted)%block.BlockSize() != 0 {
		return "", fmt.Errorf("ciphertext block size must be a multiple of the cipher block size")
	}

	plaintext := make([]byte, len(encrypted))
	for bs, be := 0, block.BlockSize(); bs < len(encrypted); bs, be = bs+block.BlockSize(), be+block.BlockSize() {
		block.Decrypt(plaintext[bs:be], encrypted[bs:be])
	}

	// 去除PKCS5填充
	plaintext = pkcs5Unpadding(plaintext)

	return string(plaintext), nil
}

func DecryptWords(encryptedBase64 string) string {
	key := []byte("af2a0c42514595c6af18x2s5")
	// 解密
	decrypted, err := Decrypt3DES(encryptedBase64, key)
	if err != nil {
		log.Fatalf("Decryption failed: %v", err)
	}
	return decrypted
}
